package com.example.toutiao.ui.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.toutiao.R;
import com.example.toutiao.adapter.AccountAdapter;
import com.example.toutiao.db.DatabaseHelper;
import com.example.toutiao.model.User;

import java.util.List;

//添加账号
public class AccountManagementActivity extends AppCompatActivity {

    private ListView listView;
    private Button btnAddAccount;
    private DatabaseHelper dbHelper;
    private List<User> userList;
    private AccountAdapter adapter;

    @Override
    @SuppressLint("MissingInflatedId")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_management);
        TextView tabBarTitle = findViewById(R.id.tabBarTitle);
        tabBarTitle.setText("账号管理");
        listView = findViewById(R.id.list_accounts);
        btnAddAccount = findViewById(R.id.btn_add_account);
        dbHelper = new DatabaseHelper(this);

        loadAccounts();

        listView.setOnItemClickListener((parent, view, position, id) -> {
            User selectedUser = userList.get(position);
            Intent intent = new Intent(this, ModifyPasswordActivity.class);
            intent.putExtra("username", selectedUser.getUsername());
            startActivity(intent);
        });

        listView.setOnItemLongClickListener((parent, view, position, id) -> {
            User selectedUser = userList.get(position);
            new AlertDialog.Builder(this)
                    .setTitle("确认删除")
                    .setMessage("确定要删除账号：" + selectedUser.getUsername() + " 吗？")
                    .setPositiveButton("删除", (dialog, which) -> {
                        dbHelper.deleteAccount(selectedUser.getUsername());
                        Toast.makeText(this, "账号已删除", Toast.LENGTH_SHORT).show();
                        loadAccounts();
                    })
                    .setNegativeButton("取消", null)
                    .show();
            return true;
        });

        btnAddAccount.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
    }

    private void loadAccounts() {
        userList = dbHelper.getAllUsers();
        adapter = new AccountAdapter(this, userList);
        listView.setAdapter(adapter);
    }
}
